<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="disable">
        <el-select v-model="queryParams.disable" placeholder="角色状态" clearable style="width: 240px" @change="handleQuery">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['system:role:add']">新增角色</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table border v-loading="loading" :data="roleList">
      <el-table-column prop="roleName" label="角色名称" width="150" show-overflow-tooltip />
      <el-table-column prop="roleCode" label="权限字符" width="150" show-overflow-tooltip />
      <el-table-column prop="roleDesc" label="角色描述" show-overflow-tooltip />
      <el-table-column prop="disable" label="状态" align="center" width="80">
        <template #default="scope">
          <el-switch
            v-model="scope.row.disable"
            :active-value="false"
            :inactive-value="true"
            active-text="启用"
            inactive-text="停用"
            inline-prompt
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <div class="table-btns">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']">编辑</el-button>
            <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['system:role:query']">详情</el-button>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:role:add', 'system:role:remove']">
              <span class="more el-dropdown-link">
                更多
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="CopyDocument" command="copy" v-if="checkPermi(['system:role:add'])">复制</el-dropdown-item>
                  <el-dropdown-item icon="Delete" divided command="delete" v-if="checkPermi(['system:role:remove'])">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.current" v-model:limit="queryParams.size" @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleCode">
          <template #label>
            <span>
              <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('SUPER_ADMIN')`)" placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              权限字符
            </span>
          </template>
          <el-input v-model="form.roleCode" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.disable">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="JSON.parse(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
           <el-input v-model="form.roleDesc" type="textarea" placeholder="请输入内容" :rows="3" maxlength="300" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import { listRole, addRole, delRole, getRole, updateRole } from "@/api/system/role"
import { checkPermi } from "@/utils/permission"

const router = useRouter()
const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict("sys_normal_disable")

const roleList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    current: 1,
    size: 10,
    roleName: undefined,
    disable: undefined
  },
  rules: {
    roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
    roleCode: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询角色列表 */
function getList() {
  loading.value = true
  listRole(queryParams.value).then(response => {
    const result = response.result || {}
    roleList.value = result.records || []
    total.value = Number(result.total)
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.current = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 角色状态修改 */
function handleStatusChange(row) {
  let text = !row.disable ? "启用" : "停用"
  proxy.$modal.confirm('确认要' + text + '"' + row.roleName + '"的角色吗?').then(function () {
    return updateRole({ roleId: row.roleId, disable: row.disable })
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
  }).catch(function () {
    row.disable = row.disable? false : true
  })
}

function handleView(row) {
  router.push("/system/role-data/view/" + row.roleId)
}

/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "copy":
      handleCopy(row)
      break
    case "delete":
      handleDelete(row)
      break
    default:
      break
  }
}

function handleCopy(row) {
  reset()
  let clone = JSON.parse(JSON.stringify(row))
  clone.roleId = undefined
  form.value = clone
  open.value = true
  title.value = "复制角色"
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除角色名称为"' + row.roleName + '"的角色?').then(function () {
    return delRole(row.roleId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    roleId: undefined,
    roleName: undefined,
    roleCode: undefined,
    disable: false,
    roleDesc: undefined
  }
  proxy.resetForm("roleRef")
}

/** 添加角色 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加角色"
}

/** 修改角色 */
function handleUpdate(row) {
  reset()
  const roleId = row.roleId
  getRole(roleId).then(response => {
    form.value = response.result || {}
    open.value = true
    title.value = "修改角色"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.roleId != undefined) {
        updateRole(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRole(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

getList()
</script>

<style lang="scss" scoped>
.table-btns {
  display: flex;
  justify-content: center;
  align-items: center;
  .more{
    margin-left: 12px;
    display: flex;
    align-items: center;
  }
}
</style>